import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/sortList/sort_item_data.dart';
import 'package:hi_common/hi_common.dart';
import 'package:drag_list/drag_list.dart';
import 'package:flutter/material.dart';

import 'sort_item.dart';

class SortList<T> extends StatefulWidget {
  final List<SortItemData<T>> items;
  final EdgeInsets padding;
  final double itemExtent;

  const SortList({
    Key key,
    this.items,
    this.itemExtent,
    this.padding,
  }) : super(key: key);

  @override
  _SortListState<T> createState() => _SortListState<T>();
}

class _SortListState<T> extends State<SortList<T>> {
  List<SortItemData<T>> items;

  @override
  void initState() {
    super.initState();

    items = widget.items;
  }

  @override
  void didUpdateWidget(SortList<T> oldWidget) {
    super.didUpdateWidget(oldWidget);

    if (widget.items != oldWidget.items) {
      items = widget.items;
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return DragList<SortItemData<T>>(
      padding: widget.padding ?? EdgeInsets.symmetric(horizontal: 30.w),
      items: items,
      itemExtent: widget.itemExtent ?? 90.w,
      builder: (context, item, handle) {
        return SortItem(data: item, handle: handle);
      },
      onItemReorder: (from, to) {
        setState(() {
          items.insert(to, items.removeAt(from));
        });
      },
      handleBuilder: (context) {
        return BaseImage(
          'assets/image/sort_list_icon.png',
          width: 40.w,
          height: 40.w,
        );
      },
    );
  }
}
